var express = require("express");
var router = express.Router();
var moment = require("moment");
const Config = require("../db/model/configModel");
const { successWithData } = require("../utils/result");

/**
 * 分页查询配置接口
 * @api {POST} /config/queryConfigByPage 分页查询配置接口
 * @apiDescription 分页查询配置接口
 * @apiName queryConfigByPage
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} page=1   页码
 * @apiBody {Number} limit=10   每页条数
 * @apiParamExample {json} Request-Example:
 *     {
 *        "page": 1,
 *        "limit": "10",
 *     }
 * @apiGroup Config
 * @apiVersion 1.0.0
 */
router.post("/config/queryConfigByPage", async function (req, res) {
  const { page, limit } = req.body;
  if (!page) {
    return res.send({ code: 500, message: "缺少page参数" });
  }
  if (!limit) {
    return res.send({ code: 500, message: "缺少limit参数" });
  }
  let offset = (page - 1) * limit;
  try {
    let result = await Config.findAndCountAll({
      limit,
      offset,
    });
    if(result && result.rows.length > 0){
      result.rows.forEach(o=>{
        if(o.channel_tag === "加密配置"){
          o.params_value = "---已配置---"
        }
      })
    }
    return res.json({ code: 200, message: "success", data: result });
  } catch (error) {
    console.log(error);
    return res.json({ code: -1, message: error });
  }
});

/**
 * 通过渠道标签查询配置接口
 * @api {POST} /config/queryListBychannelTag 通过渠道标签查询配置接口
 * @apiDescription 通过渠道标签查询配置接口
 * @apiName queryListBychannelTag
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {String} channel_tag="渠道标签"  渠道标签
 * @apiParamExample {json} Request-Example:
 *     {
 *        "channel_tag": "渠道标签",
 *     }
 * @apiGroup Config
 * @apiVersion 1.0.0
 */
router.post("/config/queryListBychannelTag", async function (req, res) {
  const { channel_tag } = req.body;
  if (!channel_tag) {
    return res.send({ code: 500, message: "缺少channel_tag参数" });
  }
  const where = {};
  if (channel_tag) {
    where["channel_tag"] = channel_tag;
  }
  try {
    let result = await Config.findAll({ where });
    if(result && result.length > 0){
      result.forEach(o=>{
        if(o.channel_tag === "加密配置"){
          o.params_value = "---已配置---"
        }
      })
    }
    return res.json(successWithData(result));
  } catch (error) {
    console.log(error);
    return res.json({ code: -1, message: error });
  }
});

/**
 * 通过key查询配置接口
 * @api {POST} /config/queryValueByKey 通过key查询配置接口
 * @apiDescription 通过key查询配置接口
 * @apiName queryValueByKey
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {String} params_key="渠道标签"  渠道标签
 * @apiParamExample {json} Request-Example:
 *     {
 *        "params_key": "key",
 *     }
 * @apiGroup Config
 * @apiVersion 1.0.0
 */
router.post("/config/queryValueByKey", async function (req, res) {
  const { params_key } = req.body;
  if (!params_key) {
    return res.send({ code: 500, message: "缺少params_key参数" });
  }
  const where = {};
  if (params_key) {
    where["params_key"] = params_key;
  }
  try {
    const result = await Config.findOne({ where });
    return res.json(successWithData(result));
  } catch (error) {
    console.log(error);
    return res.json({ code: -1, message: error });
  }
});

/**
 * @api {POST} /config/add 配置添加
 * @apiDescription 配置添加
 * @apiName add
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {String} note   备注
 * @apiBody {String} params_name   参数名称
 * @apiBody {String} params_key   参数键名
 * @apiBody {String} params_value   参数键值
 * @apiBody {String} channel_tag   渠道标签
 * @apiParamExample {json} Request-Example:
 *     {
 *        "note": '备注内容',
 *        "params_name": "参数名称",
 *        "params_key": "参数键名",
 *        "params_value", "参数键值",
 *        "channel_tag": "渠道标签"
 *     }
 * @apiGroup Config
 * @apiVersion 1.0.0
 */

router.post("/config/add", async (req, res) => {
  try {
    const { note, params_name, params_key, params_value, channel_tag } =
      req.body;
    const time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    const result = await Config.create({
      note,
      params_name,
      params_key,
      params_value,
      channel_tag,
      create_time: time,
      updated_time: time,
    });
    console.log("添加配置", result);
    return res.json({ code: 200, message: "创建成功" });
  } catch (error) {
    console.log(error);
    return res.json({
      code: 500,
      message: "创建失败:" + err,
    });
  }
});

/**
 * @api {POST} /config/del 配置删除
 * @apiDescription 配置删除
 * @apiName del
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} id  配置id
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": '1'
 *     }
 * @apiGroup Config
 * @apiVersion 1.0.0
 */
router.post("/config/del", async (req, res) => {
  try {
    const { id } = req.body;
    if (!id) {
      return res.send({ code: 500, msg: "缺少id参数" });
    }
    const result = await Config.destroy({
      where: {
        id,
      },
    });
    console.log("配置列删除", result);
    return res.json({ code: 200, message: "删除成功" });
  } catch (error) {
    return res.json({
      code: 500,
      message: "删除失败:" + err,
    });
  }
});

/**
 * @api {POST} /config/edit 配置编辑
 * @apiDescription 配置编辑
 * @apiName edit
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} id=1 配置列id
 * @apiBody {String} note   备注
 * @apiBody {String} params_name   参数名称
 * @apiBody {String} params_key   参数键名
 * @apiBody {String} params_value   参数键值
 * @apiBody {String} channel_tag   渠道标签
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": "列id",
 *        "note": '备注内容',
 *        "params_name": "参数名称",
 *        "params_key": "参数键名",
 *        "params_value", "参数键值",
 *        "channel_tag": "渠道标签"
 *     }
 * @apiGroup Config
 * @apiVersion 1.0.0
 */

router.post("/config/edit", async (req, res) => {
  try {
    const { id, note, params_name, params_key, params_value, channel_tag } =
      req.body;
    if (!id) {
      return res.send({ code: 500, msg: "缺少id参数" });
    }
    let one = await Config.findOne({
      where: {
        id,
      },
    });
    console.log("查询配置列数据", one);
    if (!one) {
      return res.json({ code: 500, message: "配置列不存在" });
    }
    const data = one.dataValues;
    if (note) {
      data.note = note;
    }
    if (params_name) {
      data.params_name = params_name;
    }
    if (params_key) {
      data.params_key = params_key;
    }
    if (params_value && params_value !== "---已配置---") {
      data.params_value = params_value;
    }
    if (channel_tag) {
      data.channel_tag = channel_tag;
    }
    data.updated_time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    console.log("配置列保存数据", data);
    const result = await Config.update(data, {
      where: {
        id,
      },
    });
    console.log("编辑配置列:", result);
    return res.json({ code: 200, message: "编辑成功" });
  } catch (error) {
    return res.json({
      code: 500,
      message: "编辑失败:" + error,
    });
  }
});
module.exports = router;
